<template>
    <div class="create-post-page">
        <h4>{{isEditMode ? '编辑文章' : '新建文章'}}</h4>
        <uploader
            action="/upload"
            :beforeUpload="commonUploadCheck"
            @file-uploaded="headleFileUploaded"
            :uploaded="uploadedData"
            class="d-flex align-items-center justify-content-center bg-light text-secondary w-100 my-4"
        >
            <h2>点击上传头图</h2>
            <template #loading>
                <div class="d-flex">
                    <div class="spinner-border text-secondary" role="status">
                        <span class="sr-only"></span>
                    </div>
                    <h2>正在上传</h2>
                </div>
            </template>
            <template #uploaded="dataProps">    <!--将上传的图片显示在上传框内供用户预览-->
                <img :src="dataProps.uploadedData.data.url">
                <div class="reUpload">点击重新上传</div>
            </template>
        </uploader>
        <!-- <input type="file" name="file" @change.prevent="headleFileChange"/> -->
        <validate-form @form-submit="onFormSubmit">
            <div class="mb-3">
                <label class="form-label">文章标题</label>
                <validate-input
                    :rules="titleRules" v-model="titleVal"
                    placeholder="请输入文章标题"
                    type="text"
                />
            </div>
            <div class="mb-3">
                <label class="form-label">文章详情</label>
                <validate-input
                    cols="100"
                    rows="10"
                    type="text"
                    tag="textarea"
                    placeholder="请输入文章详情"
                    :rules="contentRules"
                    v-model="contentVal"
                />
            </div>
            <template #submit>
                <button class="btn btn-primary btn-large">{{isEditMode ? '更新文章' : '发表文章'}}</button>
            </template>
        </validate-form>
    </div>
</template>

<script lang="ts">
import {defineComponent,ref,onMounted, PropType} from 'vue'
import {useStore} from 'vuex'
import {GlobalDataProps} from '../store'
import axios from 'axios'
import {PostProps,ResponseType,ImageProps} from '../store'
import ValidateInput, { RulesProp } from '../components/ValidateInput.vue'
import ValidateForm from '../components/ValidateForm.vue'
import { useRouter,useRoute } from 'vue-router'
import uploader from '../components/Uploader.vue'
import {beforeUploadCheck,commonUploadCheck} from '../helper'
import createMessage from '../components/createMessage'

export default defineComponent({
    name:'Login',
    components:{
        ValidateInput,
        ValidateForm,
        uploader
    },
    setup(){
        const uploadedData = ref()  //用来存储正在编辑文章的头图
        const titleVal = ref('')    //用来存储正在编辑文章的标题
        const router = useRouter()
        const route = useRoute()
        const store = useStore<GlobalDataProps>()
        //isEditMode是boolean类型,用来识别目前是否在编辑文章
        //true为正在编辑自己写的文章，false为在创建新文章，而不是编辑文章
        const isEditMode = !!route.query.id
        let imageId=''
        const titleRules:RulesProp=[
            {type:'required',message:'文章标题不能为空'}
        ]
        const contentVal=ref('')    //用来存储正在编辑文章的内容
        const contentRules:RulesProp=[
            {type:'required',message:'文章详情不能为空'}
        ]
        onMounted(()=>{
            if(isEditMode){ //如果是在编辑文章
                store.dispatch('fetchPost',route.query.id).then((rawData:ResponseType<PostProps>)=>{
                    const currentPost = rawData.data
                    if(currentPost.image){  //如果正在编辑的文章的头图存在
                        uploadedData.value = {data:currentPost.image}
                    }
                    titleVal.value = currentPost.title
                    contentVal.value = currentPost.content || ''
                })
            }
        })
        const headleFileUploaded = (rawData:ResponseType<ImageProps>)=>{    //接收从Uploader.vue传过来的上传图片数据
            if(rawData.data._id){
                imageId = rawData.data._id  //后端返回的图片的id赋值为imageId
            }
        }
        const onFormSubmit = (result:boolean)=>{    //添加文章的函数
            if(result){
                const {column,_id} = store.state.user  //获取当前登录用户的用户拥有的专栏id和用户id
                if(column){
                    const newPost:PostProps={
                        title:titleVal.value,
                        content:contentVal.value,
                        column,
                        author:_id, //用户的id,string形式
                        //createdAt:new Date().toLocaleString()
                    }
                    if(imageId){    //如果有后端返回的图片id，这个id是拿到后端图片的文件名
                        newPost.image = imageId //只用到了/upload的一个返回值_id
                    }
                    const actionName = isEditMode ? 'updatePost' : 'createPost'
                    //如果isEditMore为true,代表正在编辑文章，将id和payload发送过去
                    //如果isEditMore为false，代表发表文章，请求的action为createPost
                    const sendData = isEditMode ? {
                        id:route.query.id,
                        payload:newPost
                    } : newPost
                    store.dispatch(actionName,sendData).then((res)=>{  //res为请求后端服务器'/post'地址返回对象中的data内容
                        createMessage('发表成功，2秒后跳转到文章','success',2000)
                        setTimeout(()=>{
                            router.push({name:'column',params:{id:column}})
                        },2000)
                    })
                }     
            }
        }
        /*const headleFileChange = (e:Event)=>{   //e是input中的change事件对象
            const target = e.target as HTMLInputElement //断言为HTMLInputElement对象
            const files = target.files  //将上传的文件保存在files中
            if(files){  //如果有文件
                const uploadedFile = files[0]   //拿出来第一个文件
                const formData = new FormData() //创建FormData对象，存放要提交的文件数据，模仿form的原生原理
                formData.append(uploadedFile.name,uploadedFile) //将文件加到formData中
                axios.post('/upload',formData,{     //三个参数，第一个是提交到的后端url,第二个是提交的文件数据，第三个是设置提交头
                    headers:{
                        'Content-Type':'multipart/form-data'    //上传二进制文件需要将头部的Content-Type设置一下
                    }
                }).then((resp:any)=>{
                    console.log(resp)
                })
            }
        }*/
        /*const uploadCheck = (file:File)=>{  //检查上传的图片，是否是JPG/PNG 格式，并且图片大小不超过1Mb
            const result = beforeUploadCheck(file,{format:['image/jpeg','image/png'],size:1})
            const {passed,error} = result
            if(error ==='format'){
                createMessage('上传图片只能是 JPG/PNG 格式！','error')
            }
            if(error ==='size'){
                createMessage('上传图片大小不能超过1Mb','error')
            }
            return passed
        }*/

        return {
            titleRules,
            titleVal,
            contentVal,
            contentRules,
            onFormSubmit,
            // headleFileChange,
            // uploadCheck,
            headleFileUploaded,
            commonUploadCheck,
            uploadedData,
            isEditMode
        }
    }
})
</script>
<style>
.create-post-page .file-upload-container{
    height: 200px;
    cursor: pointer;
}
.create-post-page .file-upload-container img{
    width:100%;
    height: 100%;
    object-fit: contain;
}
.reUpload{
    width:936px;
    height:200px;
    position: absolute;
    top:220px;
    font-size: 30px;
    text-align: center;
    opacity:0;
}
.reUpload:hover{
    opacity:1;
}
</style>